<template>
  <!-- 生成合同2页面 -->
  <div class="verify-goods">
    <c-table
      size="small"
      :loading="loading"
      :data="tableOrderData"
      :columns="columns"
      @pageChange="pageChange"
      :reload="false"
      :rowKey="'id'"
    >
      <template v-slot:header-l>
        <span>核实商品</span>
      </template>
      <template v-slot:header-r>
        <a-space>
          <span class="primary cursor-pointer" @click="modifyCategoryName"
            >批量修改品名</span
          >
          <span class="primary cursor-pointer" @click="addTransportation"
            >批量添加运杂费</span
          >
        </a-space>
      </template>
      <!-- 商品品名 -->

      <div slot="categoryName" slot-scope="{ row }">
        <a-input class="input" v-model="row.categoryName"></a-input>
      </div>
      <!-- 升贴水 -->
      <div slot="premium" slot-scope="{ row }">
        <span>{{ row.premium ? row.premium : 0 }}</span>
      </div>
      <!-- 运杂费 -->
      <div slot="freight" slot-scope="{ row }">
        <div>
          <a-input-number
            v-if="row.deliveryType == '转货权'"
            class="input"
            v-model="row.categoryFee"
            :formatter="limitDecimals"
            :parser="limitDecimals"
            :min="0"
          ></a-input-number>
          <a-input-number
            v-else
            class="input"
            v-model="row.freight"
            :formatter="limitDecimals"
            :parser="limitDecimals"
            :min="0"
          ></a-input-number>
        </div>
      </div>
      <!-- 转货权 -->
      <div slot="deliveryType" slot-scope="{ row }">
        <a-auto-complete
          allowClear
          class="input"
          v-model="row.deliveryType"
          :data-source="deliveryTypeSource"
          @change="deliveryTypeChange(row)"
        />
        <!-- <a-select
          v-model="row.deliveryType"
          class="input"
          @change="deliveryTypeChange(row)"
        >
          <a-select-option
            v-for="(item, idx) in deliveryTypeArr"
            :value="item.value"
            :key="idx"
            >{{ item.value }}</a-select-option
          >
        </a-select> -->
      </div>
      <!-- 实物库存编号 -->
      <div slot="entityInventory" slot-scope="{ row }">
        <div
          v-if="
            (row.entityInventory && row.entityInventory.length == 0) ||
              !row.entityInventory
          "
        >
          无
        </div>
        <div v-else>
          <span
            class="primary"
            v-for="(item, index) in row.entityInventory"
            :key="index"
          >
            {{ item.entityInventoryCode }}
            <br />
          </span>
        </div>
      </div>

      <!-- 实重 -->
      <div slot="weight" slot-scope="{ row }">
        <div
          v-if="
            (row.entityInventory && row.entityInventory.length == 0) ||
              !row.entityInventory
          "
        >
          <a-input-number
            :formatter="limitDecimals"
            :parser="limitDecimals"
            class="input"
            v-model="row.amount"
            :min="0"
          ></a-input-number>
        </div>
        <div v-else>
          <span v-for="(item, index) in row.entityInventory" :key="index">
            {{ item.amount }}
            <br />
          </span>
        </div>
      </div>
    </c-table>
    <div class="total">
      <p>合计</p>
      <div class="total-content">
        <p class="flex-between">
          <span>商品总量（吨）：</span>
          <span class="danger">{{ totalAmount.toFixed(2) }}</span>
        </p>
        <p class="flex-between" v-if="discountVisible">
          <span>合同折扣（元）：</span>
          <span class="danger">￥{{ discount }}</span>
        </p>
        <p class="flex-between">
          <span>合同总价（元）：</span>
          <span class="danger" @click="editContractSum">
            <c-icon v-if="identity == 2" type="tousujianyi"></c-icon>
            ￥{{ afterDiscount.toFixed(2) }}
          </span>
        </p>
      </div>
    </div>
    <div class="preview">
      <a-space>
        <a-button @click="toBack">返回修改</a-button>
        <a-button type="primary" @click="onPreview">合同预览</a-button>
      </a-space>
    </div>
    <c-modal
      v-model="editContractSumVisible"
      title="合同折扣"
      :width="400"
      :okLoading="partDealAmountLoading"
      @cancel="editContractSumVisible = false"
      @ok="submitDiscount"
    >
      <div class>
        <p class="flex-between flex-align-c">
          <span>合同总价：</span>
          <span class="danger">￥{{ totalPrice.toFixed(2) }}</span>
        </p>
        <p class="flex-between flex-align-c">
          <span>合同折扣：</span>
          <span>
            <a-input-number
              :formatter="limitDecimals"
              :parser="limitDecimals"
              class="contract-discount"
              v-model="discount"
              :min="0"
            ></a-input-number>
          </span>
        </p>
        <p class="flex-between flex-align-c">
          <span>显示折扣：</span>
          <span>
            <a-switch v-model="showDiscount" />
          </span>
        </p>
        <p class="flex-between flex-align-c">
          <span>折扣后合同总价：</span>
          <span class="danger">￥{{ afterDiscount.toFixed(2) }}</span>
        </p>
      </div>
    </c-modal>
    <c-modal
      v-model="modifyGoodsNameVisible"
      title="批量修改品名"
      :width="400"
      :okLoading="partDealAmountLoading"
      @cancel="modifyGoodsNameVisible = false"
      @ok="submitModifyGoodsName"
    >
      <div class="tc">
        <p class="tl">
          将该合同的所有品名统一修改为：
          <a-input
            v-model="updateCategoryName"
            placeholder="请输入品名"
            class="goodsNameInput"
          ></a-input>
        </p>
      </div>
    </c-modal>
    <a-modal
      v-model="modifyTransportationVisible"
      title="批量修改运杂费"
      :width="500"
      :okLoading="partDealAmountLoading"
      @cancel="modifyTransportationVisible = false"
      @ok="submitModifyTransportation"
    >
      <a-table
        size="small"
        :rowKey="'id'"
        :columns="moduleColumns"
        :data-source="transportationArr"
        :pagination="false"
      >
        <div class="freight" slot="freight" slot-scope="row">
          <a-input-number
            class="freightInputPro"
            type="number"
            placeholder="请输入运杂费"
            v-model="row.freight"
          ></a-input-number>
        </div>
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { sellerPreviewContract, buyerPreviewContract } from "@/api/contract";
import { random } from "@/util/common";
import { getCurIdentity } from "@/util/common";
import { filterOption, objToHeavy } from "../common/public";

const pageData = [
  {
    id: "1",
    categoryName: "广州"
  },
  {
    id: "2",
    categoryName: "广州众咖"
  }
];
const moduleColumns = [
  {
    title: "仓库简称",
    dataIndex: "warehouseShortName",
    key: "warehouseShortName"
  },

  {
    title: "运杂费（元/吨）",
    scopedSlots: { customRender: "freight" }
  }
];

export default {
  name: "VerifyGoods",
  data() {
    return {
      showDiscount: false, //是否显示折扣
      discount: 0, // 折扣
      editContractSumVisible: false,
      loading: false,
      submitLoading: false,
      modifyTransportationVisible: false, //批量修改运杂费
      modifyGoodsNameVisible: false,
      discountVisible: false,
      partDealAmountLoading: false,
      updateCategoryName: "",
      data: {},
      transportationArr: [], //批量添加运杂费窗口
      pageData,
      moduleColumns,
      form: {},
      tableOrderData: [],
      deliveryTypeSource: ["转货权", "买家自提", "卖家送货", "加工单"]
      // deliveryTypeArr: [
      //   {
      //     value: "转货权"
      //   },
      //   {
      //     value: "买家自提"
      //   },
      //   {
      //     value: "卖家送货"
      //   },
      //   {
      //     value: "加工单"
      //   }
      // ]
    };
  },
  computed: {
    identity() {
      return getCurIdentity(); //1买家，2卖家
    },
    // 商品总价
    totalPrice() {
      let res = 0;
      let priceType = this.createContractparams.priceType;
      for (let item of this.tableOrderData) {
        if (item.entityInventory && item.entityInventory.length !== 0) {
          item.amount = item.entityInventory[0].amount;
        }
        //1点价： (基价+升贴水+运杂费)*实重
        //2确定价: (含税单价+运杂费)*实重
        let freight =
          item.deliveryType == "转货权" ? item.categoryFee : item.freight;
        switch (priceType) {
          case 1:
            res += Number(
              item.amount * (item.basePrice + item.premium + freight)
            );
            break;
          case 2:
            res += Number(item.amount * (item.basePrice + freight));
            break;
        }
      }
      return res;
    },
    // 商品总数
    totalAmount() {
      let res = 0;
      for (let item of this.tableOrderData) {
        if (item.entityInventory && item.entityInventory.length !== 0) {
          item.amount = item.entityInventory[0].amount;
        }
        res += Number(item.amount ? item.amount : 0);
      }
      return res;
    },
    //合同折扣后价格
    afterDiscount() {
      let res = 0;
      res = Number(this.totalPrice) - Number(this.discount);
      return res >= 0 ? res : 0;
    },
    columns() {
      let res = [
        {
          title: "商品品名",
          key: "categoryName",
          scopedSlots: { customRender: "categoryName" }
        },
        {
          title: "品牌",
          key: "brand",
          dataIndex: "brand"
        },
        {
          title: "规格",
          dataIndex: "spec",
          key: "spec"
        },
        {
          title: "材质",
          dataIndex: "material",
          key: "material"
        },
        {
          title: "其他",
          dataIndex: "other",
          key: "other"
        },
        {
          title: "仓库简称",
          dataIndex: "warehouseShortName",
          key: "warehouseShortName"
        },
        {
          title: "基价（元）",
          key: "basePrice",
          dataIndex: "basePrice"
        },
        {
          title: "升贴水（元）",
          key: "premium",
          scopedSlots: { customRender: "premium" }
        },
        {
          title: "运杂费(元/吨)",
          key: "freight",
          scopedSlots: { customRender: "freight" }
        },
        {
          title: "数量(吨)",
          key: "dealAmount",
          dataIndex: "dealAmount"
        },
        {
          title: "实物库存单号",
          key: "entityInventory",
          scopedSlots: { customRender: "entityInventory" }
        },
        {
          title: "实重(吨)",
          key: "weight",
          scopedSlots: { customRender: "weight" }
        },
        {
          title: "交货方式",
          key: "deliveryType",
          scopedSlots: { customRender: "deliveryType" }
        }
      ];
      return res;
    },
    createContractparams() {
      return this.$storage.s_get("createContractparams");
    },
    createContractOrder() {
      return this.$storage.s_get("createContractOrder");
    }
  },
  created() {
    //拆分初始化数据
    this.tableOrderData = this.splitInventory(this.createContractOrder);
  },

  methods: {
    objToHeavy,
    random,
    filterOption,
    limitDecimals(value) {
      const reg = /^(-)*(\d+)\.(\d\d).*$/;
      let result = 0;
      if (typeof value === "string") {
        result = !isNaN(Number(value)) ? value.replace(reg, "$1$2.$3") : "";
      } else if (typeof value === "number") {
        result = !isNaN(-1) ? String(value).replace(reg, "$1$2.$3") : "";
      } else {
        result = 0;
      }
      return result;
    },
    // 多个实物库存（拆分）
    splitInventory(data) {
      let res = [];
      data.forEach(item => {
        let categoryFee = item.categoryFee ? item.categoryFee : 0;
        let freight = item.freight ? item.freight : 0;
        let premium = item.premium ? item.premium : 0;
        let dealAmount = item.dealAmount ? item.dealAmount : 0;
        let entityInventory = item.entityInventory;
        if (entityInventory && entityInventory.length > 0) {
          entityInventory.forEach(i => {
            let obj = {
              ...item,
              premium: premium,
              categoryFee: categoryFee,
              entityInventory: [
                {
                  id: i.id,
                  version: i.version,
                  entityInventoryCode: i.entityInventoryCode,
                  amount: i.weight, //注：修改名字amount，预览合同参数名称
                  categoryName: item.categoryName,
                  deliveryType: item.deliveryType,
                  freight: item.deliveryType == "转货权" ? categoryFee : freight
                }
              ],
              id: i.id
            };
            res.push(obj);
            return res;
          });
        } else {
          let obj = {
            ...item,
            amount: dealAmount, //注：没有实重的时候实重等于成交吨数(本无，新赋值)
            categoryFee: categoryFee,
            premium: premium,
            id: item.orderId,
            entityInventory: []
          };
          res.push(obj);
        }
      });
      return res;
    },
    //返回上一步
    toBack() {
      this.$emit("onStepChange", 0);
    },
    //修改商品名称
    modifyCategoryName() {
      this.modifyGoodsNameVisible = true;
    },
    //批量添加运杂费
    addTransportation() {
      this.transportationArr = [];
      this.modifyTransportationVisible = true;
      this.tableOrderData.forEach(item => {
        let obj = {
          freight: "",
          warehouseShortName: item.warehouseShortName,
          id: item.id
        };
        this.objToHeavy(obj, this.transportationArr, "warehouseShortName");
      });
    },
    //运杂费窗口提交
    submitModifyTransportation() {
      this.tableOrderData.forEach(item => {
        this.transportationArr.forEach(i => {
          let freight = i.freight;
          if (item.warehouseShortName == i.warehouseShortName) {
            if (freight) {
              item.freight = freight;
              item.categoryFee = freight;
              if (item.entityInventory.length != 0) {
                item.entityInventory[0].freight = freight;
              }
            }
          }
        });
      });
      this.modifyTransportationVisible = false;
    },
    //修改品名提交
    submitModifyGoodsName() {
      if (!this.updateCategoryName) {
        this.$message.warning("请输入品名");
        return;
      }
      this.tableOrderData.forEach(item => {
        item.categoryName = this.updateCategoryName;
      });
      this.modifyGoodsNameVisible = false;
    },
    //预览合同
    onPreview() {
      let parmas = this.createContractparams;
      let orderArrParmas = [];
      orderArrParmas = this.filterOption(
        this.tableOrderData,
        // item :[item]
        item => {
          return {
            orderId: item.orderId,
            version: item.version,
            entityInventory: item.entityInventory
          };
        },
        "entityInventory",
        // entityInventory :[i]
        i => {
          return {
            categoryName: i.categoryName,
            deliveryType: i.deliveryType,
            freight: i.deliveryType == "转货权" ? i.categoryFee : i.freight,
            amount: i.amount
          };
        },
        //判断实重是否为空
        "notAmountTips",
        //判断商品品名是否为空
        "notCategoryNameTips"
      );

      this.loading = true;
      let requesFun;
      this.identity === 1
        ? (requesFun = buyerPreviewContract)
        : (requesFun = sellerPreviewContract);
      let queryParmas = {
        deliveryPlaceType: parmas.deliveryPlaceType,
        beforeChangeCompanyId: parmas.beforeChangeCompanyId,
        currentCompanyId: parmas.currentCompanyId,
        dealCompanyId: parmas.dealCompanyId,
        contractCodeType: parmas.contractCodeType,
        contractCode: parmas.contractCode,
        signPlace: parmas.signPlace,
        signDate: this.$timeToTimestamp(parmas.signDate, 10)
          ? this.$timeToTimestamp(parmas.signDate, 10)
          : "",
        deliveryPlace: parmas.deliveryPlace,
        deliveryDate: this.$timeToTimestamp(parmas.deliveryDate, 10)
          ? this.$timeToTimestamp(parmas.deliveryDate, 10)
          : "",
        categoryId: parmas.categoryId,
        priceType: parmas.priceType,
        contractTemplateId: parmas.contractTemplateId,
        order: orderArrParmas,
        discount: Number(Number(this.discount).toFixed(2)),
        showDiscount: this.showDiscount,
        totalAmount: Number(Number(this.totalAmount).toFixed(2)),
        totalPrice: Number(Number(this.afterDiscount).toFixed(2))
      };
      requesFun(queryParmas)
        .then(res => {
          this.data = res;
          this.$emit("onStepChange", 2, [res], [res]);
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    pageChange(pagination) {
      this.pageNum = pagination;
    },
    editContractSum() {
      this.editContractSumVisible = true;
    },

    //合同折扣确认提交
    submitDiscount() {
      if (this.totalPrice <= this.discount) {
        this.$message.warning("最大折扣不能等于合同总价");
        this.discount = 0;
        return;
      }
      this.editContractSumVisible = false;
      if (Number(this.discount) > 0) {
        this.discountVisible = true;
      } else {
        this.discountVisible = false;
      }
      this.discount = Number(this.discount).toFixed(2);
    },
    //转货权切换（计算运杂费）
    deliveryTypeChange(row) {
      let deliveryType = row.deliveryType;
      let storageContractOrderDatas = this.splitInventory(
        this.$storage.s_get("createContractOrder")
      );
      this.tableOrderData.forEach(item => {
        let entityInventory = item.entityInventory;
        storageContractOrderDatas.forEach(origin => {
          if (origin.id == row.id) {
            row.categoryFee = origin.categoryFee;
            row.freight = origin.freight;
          }
        });

        if (deliveryType == "转货权") {
          if (entityInventory.length != 0) {
            entityInventory[0].freight = row.categoryFee;
          }
        } else {
          if (entityInventory.length != 0) {
            entityInventory[0].freight = row.freight;
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.freightInputPro {
  width: 120px !important;
}
.contract-discount {
  width: 255px;
  margin-right: 5px;
}
.verify-goods {
  background: #fff;
  padding: 30px;
  .preview {
    text-align: center;
    margin: 30px;
  }
  .input {
    width: 100px !important;
  }
  .goodsNameInput {
    width: 100% !important;
    margin-top: 10px;
  }
  .total {
    margin-top: 30px;
    .total-content {
      border: 1px solid #e8e8e8;
      padding: 10px 20px;
    }
  }
}
</style>
